import time
import paho.mqtt.client as mqtt


class TMqtt:
    def __init__(self):
        self.mqttCode = ""
        self.settings={
            "host":"",
            "port":0,
            "uid":"",
            "pwd":"" ,
            "subTopics":[],
            "reconnectTime": 5
        }
        self.client=  mqtt.Client()
        self.clientId = ""
        '''
        self.onConnectSuccess= None
        self.onConnectFail = None
        self.onDisConnect = None
        self.onMsg=None
        '''
        self.forceClosed = False
        self.onMsg = None

    def reset(self):
        try:
            self.disconnect()
            self.connect()
        except Exception as er:
            print(er)
    def connect(self):
        res = {
            "status" :0
        }
        try:
            self.disconnect()
            self.forceClosed = False
            clientId = self.clientId if self.clientId!="" else 'mq-'+str(int(1000*time.time()))
            self.clientId = clientId
            host =  self.settings['host']
            port =  self.settings['port']
            uid =  self.settings['uid']
            pwd =  self.settings['pwd']
            #self.client=  mqtt.Client(mqtt.CallbackAPIVersion.VERSION2 , client_id= clientId)
            self.client=  mqtt.Client(client_id= clientId)
            self.client.on_connect = self.client.on_connect
            self.client.on_connect_fail = self.on_connect_fail
            self.client.on_disconnect = self.on_disconnect
            self.client.on_message = self.on_message
            self.client.username_pw_set(uid , pwd )
            code = self.client.connect(host, port, 60)
            if code ==0 :
                for topic in self.settings['subTopics']:
                    self.client.subscribe(topic)
            print(f'connect to mqtt server.{host}:{port}.[{code}]')
            self.client.loop_start()
            res['status']=1
        except Exception as er:
            print(er)
        return res
    def disconnect(self):
        res = {
            "status" :0
        }
        try:
            self.forceClosed = True
            if( self.client!=None):
                if self.client.is_connected():
                    self.disconnect()
                self.client = None
        except Exception as er:
            print(er)
        return res
    def on_connect(self , client, userdata, flags, reason_code, properties):
        try:
            print(f"on mq client connected .code:{flags} , reason:{reason_code}")
            for topic in self.settings['subTopics']:
                self.client.subscribe(topic)
        except Exception as er:
            print(er)
    def on_connect_fail(self , client, userdata):
        try:
            print('---------  connect mqtt server fail!  ---------------')
            if not self.forceClosed:
                delay = self.settings['reconnectTime']
                time.sleep(delay)
                self.connect()
        except Exception as er:
            print(er)
    def on_disconnect(self , disconnect_flags, reason_code, properties):
        try:
            print('---------  disconnect from mqtt fail!  ---------------')
            print(f'disconnect_flags:{disconnect_flags}, reason_code:{reason_code}, properties:{properties}')
            print('-------------------------------------------------------')
            if not self.forceClosed:
                delay = self.settings['reconnectTime']
                time.sleep(delay)
                self.connect()
        except Exception as er:
            print(er)
    def on_message(self , client, userdata, message):
        try:
            if self.onMsg!=None:
                self.onMsg(message)
        except Exception as er:
            print(er)
